<template>
	<view style="width: 100%;padding: 0;margin: 0;">
		<el-header class="header-sticky-top" :style="'opacity: '+opacity+';height: 45px;'">
			<view style="cursor:pointer;width: auto;display: flex;justify-content: center;align-items: center;">
				<view style="margin:0px 10px;" @click="sendDataToParent">
					<uv-icon size="38" :name="aside?'list':'list-dot'" color="#C6000B"></uv-icon>
					<!-- /static/index/svg/logo_left.svg hidden-xs-only -->
				</view>
				<el-link href="/" :underline="false"
					style="display: flex;justify-content: center;align-items: center;height: 45px;">
					<el-image @click="routed('/')"
						style="display: flex;justify-content: center;align-items: center;width: 95px; height: auto"
						src="/static/index/svg/logo.svg" fit="fill" mode="widthFix"></el-image>
				</el-link>
			</view>


			<view class="ai_search">
				<el-input class="searchInput" v-if="searchShow" placeholder="AI智能搜索" v-model="search" clearable
					@clear="$emit('searchclear')" @blur="$emit('searchblur')">
					<!-- <template slot="prefix">
						<el-link href="/" :underline="false" @click="routed('/')"
							style="display: flex;justify-content: center;align-items: center;width: 65px;background-color: rgba(0, 0, 0, 0);">
							<uv-icon width="65" height="35" name="/static/index/svg/logo.svg"></uv-icon>
						</el-link>
					</template> -->
					<template slot="append">
						<view @click="$emit('searchclick',search)"
							style="display: flex;justify-content: center;align-items: center;width: 20px;">
							<uv-icon size="30" name="search"></uv-icon>
						</view>
					</template>
				</el-input>
			</view>
			<uv-icon v-if="!searchShow" size="30" name="search" @click="searchClick"></uv-icon>

			<!-- <el-tooltip class="item" effect="dark" content="原画" placement="bottom">
				<el-link href="https://api.readend.com" type="primary">跳转到旧版</el-link>
			</el-tooltip> -->
			<view :style="'display: flex;justify-content: center;align-items: center;color:'+deepColor">
				<view v-if="devel&&false"
					style="margin-left: 5px;margin-right: 15px;display: flex;justify-content: flex-start;align-items: center;">
					<view v-if="theme" style="font-size: 15px;color: #dddddd;">月</view>
					<view v-else style="font-size: 15px;">日</view>
					<el-switch style="margin-left: 5px;" @change="darks" v-model="theme" active-color="#13ce66"
						inactive-color="#C6000B">
					</el-switch>
				</view>

				<view v-if="false" class="cursor-pointer" @click="routed('/pages/my/recharge')"
					style="display: flex;justify-content: flex-start;align-items: center;background-color: #F1F2F8;border-radius: 15px;padding: 5px;">
					<el-image style="width: 23px; height: auto;" :src="img" fit="fill"></el-image>
					<view class="hidden-md-and-down"
						style="font-size: 15px; margin-left: 5px;margin-right: 5px;display: flex;justify-content: flex-start;">
						{{ (vuex_user.reset+vuex_user.balance/vuex_user.exchange||0).toFixed(1)}}
					</view>
				</view>
				<el-image v-if="false"
					style="width: 40px; height: 40px;margin-right: 10px;display: flex;justify-content: center;align-items: center;"
					src="/static/index/svg/notice.svg" fit="fill"></el-image>
				<view v-if="false" class="cursor-pointer" @click="routed('pages/my/index')" style="margin-right: 5px;">
					<i class="el-icon-loading"></i>
					<el-image style="width: 40px; height:40px;border-radius: 50%;" :src="vuex_user.portrait"
						fit="cover">
						<div slot="error" class="image-slot">
							<el-image style="width: 40px; height:40px;border-radius: 50%;" src="/static/ai.svg"
								fit="cover">
							</el-image>
						</div>
					</el-image>
				</view>
			</view>
		</el-header>
		<uv-modal ref="modal" :title="data.msg" @confirm="confirm" @close="routed(return_url)">
			<view class="slot-content">
				<uv-icon v-if="data.price" name="checkmark-circle-fill" :label="'充值金额：'+price" color="#2979ff"
					size="28">
				</uv-icon>
				<view v-else>
					<view v-if="data.content">{{data.content}}</view>
					<view v-if="data.remarks">{{data.remarks}}</view>
					<view v-if="data.time" style="margin-top: 5px;">
						<uv-text :text="'更新时间：'+timeAt()"></uv-text>
					</view>
				</view>
				<!-- <el-result icon="success" :title="msg" :subTitle="'充值金额：'+price"></el-result> -->
			</view>
		</uv-modal>
	</view>
</template>

<script>
	import {
		io
	} from 'socket.io-client';
	// import io from '@/static/js/uniapp.socket.io.js';
	// import io from '@hyoga/uni-socket.io';
	import config from '@/common/config'
	import {
		uploadFile,
		getUser,
		apiId
	} from '@/common/api.js';
	import helangCompress from '@/components/compress/compress.vue';
	export default {
		components: {
			// 注册组件
			helangCompress
		},
		props: {
			deepColor: {
				type: String,
				default: '#282C34'
			},
			shallowColor: {
				type: String,
				default: '#808080'
			},
			lightColor: {
				type: String,
				default: '#ccc'
			},
			opacity: {
				type: Number,
				default: 1
			},
			return_url: {
				type: String,
				default: '/'
			},
			state: {
				type: Boolean,
				default: false
			},
		},
		data() {
			return {
				fill: config.fill,
				theme: false,
				aside: true,
				socket: null,
				data: "",
				reconnectAttempts: 0, // 重连次数
				devel: process.env.NODE_ENV === 'development',
				img: config.img,
				tabbar: config.tabbar,
				tabbarsValue: '/',
				search: '',
				searchShow: true,
				ais: [{
						name: '对话',
						icon: 'dialogue',
						checked: false,
						click: '/pages/chat/index',
					},
					{
						name: '识别',
						icon: 'distinguish',
						checked: false
					},
					{
						name: '图片',
						icon: 'picture',
						checked: false,
						click: '/pages/painting/index',
					},
					{
						name: '视频',
						icon: 'video',
						checked: false,
						click: '/pages/video/index',
					},
					{
						name: 'AI-音频',
						icon: 'audio',
						checked: false,
						click: '/pages/music/index',
					}
				],
			}
		},
		mounted() {
			this.tabbarsValue = this.pages();
			if (this.$uv.os() != 'windows') {
				this.aside = true;
				this.searchShow = false;
			}
			this.$emit('custom-event', this.aside);
			this.ws();

			apiId('/notice', {
				custom: {
					auth: true,
					toast: false,
				},
				params: {
					ai: this.aiApi
				}
			}).then(e => {
				console.log(e);
				if (e._id != uni.getStorageSync('noticeId')) {
					console.log(e._id, '=>', uni.getStorageSync('noticeId'));
					this.data = e;
					this.$refs.modal.open();
				}
			})
			// if (!this.devel) {
			// }
			// var msg = {
			// 	type: 'msg',
			// 	msg: '充值成功！',
			// 	data: {
			// 		price: 10
			// 	}
			// };
			// this.msg = msg.msg;
			// this.price = msg.data.price;
			// this.$refs.modal.open();
		},
		watch: {
			// 监听data数据的变化
			obj(newVal, oldVal) {
				this.$emit('obj', newVal);
			},
			state(newVal, oldVal) {
				this.aside = newVal;
			},
			// #ifndef VUE3
			$route: {
				immediate: true,
				handler(newRoute) {
					this.handlerRoute(newRoute)
				}
			},
			// #endif
			// #ifdef VUE3
			$route(newRoute) {
				this.handlerRoute(newRoute)
			}
			// #endif
		},
		beforeDestroy() {
			// 在页面销毁前断开socket连接
			if (this.socket) {
				this.socket.disconnect();
				this.socket = null;
			}
		},
		methods: {
			searchClick(e) {
				console.log(e);
				this.searchShow = true
			},
			pages() {
				var pages = getCurrentPages() // 获取栈实例
				let currentRoute = pages[pages.length - 1].route; // 获取当前页面路由
				let currentPage = pages[pages.length - 1]['$page']['fullPath'] //当前页面路径(带参数)
				return currentPage.split('/')[2];
			},
			timeAt() {
				if (this.data.startTime) {
					// return uni.$uv.date('2023-08-06', 'yyyy年mm月dd日 hh时MM分ss秒');
					return uni.$uv.date(new Date(this.data.startTime).getTime(), 'yyyy-mm-dd')
				}
			},
			confirm() {
				uni.setStorageSync('noticeId', this.data._id);
				this.$refs.modal.close();
			},
			ws() {
				var that = this;
				//判断当前浏览器是否支持WebSocket
				if (this.socket == null && this.vuex_token) {
					var mid = uni.$uv.guid(10);
					if ('WebSocket' in window) {
						this.socket = io(this.vuex_user.hostnames, {
							query: {
								mid: mid
							},
							upgrade: false,
							secure: true,
							rejectUnauthorized: false,
							auth: {
								authorization: "Bearer " + this.aes_decrypt(this.vuex_token)
							},
							transports: ['websocket', 'polling'],
							timeout: 5000,
							// 'polling'
						});
					} else {
						alert('Not support socket.io')
					}
					this.socket.on('connect', (e) => {
						// console.log('ws 已连接', e);
						// 连接建立后，可以进行事件监听或数据发送操作
						// this.socket.emit('message', {
						// 	time: +new Date()
						// });
						// this.socket.timeout(5000).emit('request', {
						// 	foo: 'bar'
						// }, (err, response) => {
						// 	if (err) {
						// 		// the server did not acknowledge the event in the given delay
						// 	} else {
						// 		console.log(response.status); // 'ok'
						// 	}
						// });
					});
					// 单推
					this.socket.on(this.vuex_user._id, (msg) => {
						if (msg.code == 200) {
							this.data = msg.data
							if (msg.data.type == '充值') {
								that.getUsers()
								that.$refs.modal.open();
							} else if (msg.data.type == 'refresh') {
								that.getUsers();
								that.$emit('refresh', msg);
							} else {
								uni.$uv.toast('ws ,' + msg);
							}
						} else {
							console.log('ws', JSON.stringify(msg))
						}
					});
					// 监听服务器推送的消息
					this.socket.on('message', (msg) => {
						console.log('message ', msg);
						uni.$uv.toast(msg.msg);
						// if (msg.type == 'msg') {

						// }
					});
					// 监听错误事件
					this.socket.on('connect_error', (msg) => {
						console.log('ws connect_error', JSON.stringify(msg))
						if (msg.type === 'TransportError' || msg === 'transport error') {
							this.socket.disconnect();
							this.socket = null;
							return;
						}
					});
					// 监听错误事件
					this.socket.on('error', (msg) => {
						console.log('ws error', JSON.stringify(msg))
						if (msg.code === 401) {
							this.socket.disconnect();
							this.socket = null;
							return;
						}
					});
					// 监听连接断开事件
					this.socket.on('disconnect', (msg) => {
						console.log('ws disconnect', msg);
						if (msg === 'io client disconnect' || msg === 'transport error') {
							// 如果是服务器主动断开连接，则不重连
							this.socket.disconnect();
							this.socket = null;
							return;
						}
						// this.reconnectAttempts++;
						// console.log(`断开连接，正在尝试重连... (${this.reconnectAttempts})`);
						// // 设置延时，防止过快重连
						// setTimeout(() => {
						// 	that.socket.open(); // 尝试重新连接
						// }, 5000);
						// if (this.devel) {
						// 	if (this.socket) {
						// 		this.socket.disconnect();
						// 		// this.socket = null;
						// 	}
						// }
						// console.log('Disconnected from socket.io server', msg);
					});

					// 单推错误
					this.socket.on(mid, (msg) => {
						console.log(msg);
						if (msg.type === 'TransportError') {
							this.socket.disconnect();
							this.socket = null;
							return;
						}
					});
				}
			},
			sendDataToParent() {
				this.aside = !this.aside;
				this.$emit('custom-event', this.aside);
			},
			// 删除图片
			deletePic(event) {
				this.fileList.splice(event.index, 1)
			},
			darks() {
				this.setAppTheme(this.theme ? 'dark' : 'light');
				uni.setStorageSync('theme', this.theme ? 'dark' : 'light');
				// uni.setSystemInfoSync(e ? 'dark' : 'light');
				// console.log(uni.getSystemInfoSync('theme'));
			},
			onThemeChange(res) {
				console.log(theme);
				// 根据系统主题设置应用主题
				const theme = res.theme === 'dark' ? 'dark' : 'light';
				this.setAppTheme(theme);
			},
			setAppTheme(theme) {
				// 设置应用主题，例如更改背景颜色、文字颜色等
				document.body.style.backgroundColor = theme === 'dark' ? '#282C34' : '#fff';
				document.body.style.frontColor = theme === 'dark' ? '#fff' : '#282C34';
				// if (theme === 'dark') {
				// 	// 设置深色模式下的样式
				// 	uni.setNavigationBarColor({
				// 		frontColor: '#ffffff',
				// 		backgroundColor: '#000000',
				// 		animation: {
				// 			duration: 400,
				// 			timingFunc: 'easeIn'
				// 		}
				// 	});
				// 	// 其他深色模式下的样式设置
				// } else {
				// 	// 设置浅色模式下的样式
				// 	uni.setNavigationBarColor({
				// 		frontColor: '#000000',
				// 		backgroundColor: '#ffffff',
				// 		animation: {
				// 			duration: 400,
				// 			timingFunc: 'easeIn'
				// 		}
				// 	});
				// 	// 其他浅色模式下的样式设置
				// }
			},
			getUsers() {
				getUser({
					custom: {
						auth: true,
						catch: false,
					}
				}).then(e => {
					this.$uv.vuex('vuex_user', e);
				}).catch(e => {})
			},
			handlerRoute(newRoute) {
				const width = uni.$uv.sys().screenWidth
				if (width >= 768) {
					let path = newRoute.path
					// let comp
					// if (path === '/') {
					// 	comp = 'chat'
					// } else {
					// 	comp = path.split('/')[2]
					// }
					// console.log(path);
					if (path == '/pages/my/index') {
						let path = '/pages/my/invite'
						uni.$uv.route({
							url: path,
							type: "redirectTo",
						});
					}
					if (path == '/pages/community/index') {
						let path = '/pages/community/dialogue'
						uni.$uv.route({
							url: path,
							type: "redirectTo",
						});
					}
				}
			},
			routed(url) {
				uni.$uv.route({
					url: url,
					// intercept(params, next) {
					// 	// console.log(params, next)
					// 	uni.showLoading({
					// 		title: '等待中...'
					// 	})
					// 	// 模拟处理等待
					// 	setTimeout(() => {
					// 		uni.hideLoading();
					// 		next(true);
					// 	}, 1000)
					// }
				})
			}
		}
	}
</script>

<style scoped lang="scss">
	.header-sticky-top {
		// height: 39px;
		position: -webkit-sticky;
		position: sticky;
		top: 0;
		/* 粘性定位的容器距离顶部的距离 */
		z-index: 10;
		/* 确保菜单在页面内容之上 */
		width: 100%;
		left: 0px;
		right: 0px;
		display: flex;
		justify-content: space-between;
		align-items: center;
		border-bottom: 1px solid #E9ECEF;
		margin: 0px;
		padding: 0px 12px 0px 0px;

		.ll {
			font-size: 15px;
			color: #808080;
			margin-left: 23px;
		}

		.ai_search {
			width: 100%;
			display: flex;
			justify-content: center;

			.searchInput {
				overflow: hidden;
				cursor: pointer;
				margin: 0px 10px;
				height: 38px;
				max-width: 1000px;
				border: 1px solid #808080;
				border-radius: 15px;
				
				// ::v-deep .el-input__prefix {
				// 	width: 80px;
				// 	font-size: 60px;
				// }

				::v-deep .el-input__inner {
					// padding-left: 80px;
					width: 100%;
					height: 38px;
					border: 0px;
				}

				::v-deep .el-input-group__append {
					border-left: 1px solid #808080;
				}
			}

		}

	}
</style>